package com.lemon.smartsafety.ui.activity.fire.item.inspection;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.android.http.HttpUtils;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.DataInfo;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.RefreshViewEntity;
import com.lemon.smartsafety.entity.event.datacoll.BuildingAddCheckItemEvent;
import com.lemon.smartsafety.entity.event.datacoll.BuildingItemCountEvent;
import com.lemon.smartsafety.entity.event.datacoll.BuildingPositionRefreshEvent;
import com.lemon.smartsafety.entity.event.datacoll.BuildingPositionRemarkEvent;
import com.lemon.smartsafety.entity.event.datacoll.FloorNumItemEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.event.safe_manager.BuildingListFragmentRefresh;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingIndexVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingVo;
import com.lemon.smartsafety.http.HttpBack;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.SafeDataServices;
import com.lemon.smartsafety.result.BaseMode;
import com.lemon.smartsafety.result.fire.SuperviseCompanyResult;
import com.lemon.smartsafetynew.ui.activity.base.NewBaseActivity;
import com.lemon.smartsafety.ui.activity.fire.FirefightingUtil;
import com.lemon.smartsafety.ui.fragment.fire.situation.FireInspectionBuildingFloorFragment;
import com.lemon.smartsafety.ui.fragment.fire.situation.FireInspectionBuildingPositionFragment;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.utils.photo.GlideImageLoader;

import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;

import butterknife.Bind;
import butterknife.OnClick;

/**
 *   现场检查楼层和方位
 */
public class FireInspectionBuildItemActivity extends NewBaseActivity {


    @Bind(R.id.iv_build)
    ImageView iv_build;
    @Bind(R.id.tv_build_title)
    TextView tvBuildTitle;
    @Bind(R.id.tv_type)
    TextView tvType;
    @Bind(R.id.tv_east)
    TextView tvEast;
    @Bind(R.id.tv_south)
    TextView tvSouth;
    @Bind(R.id.tv_west)
    TextView tvWest;
    @Bind(R.id.tv_north)
    TextView tvNorth;
    @Bind(R.id.tv_remark)
    TextView tvRemark;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.mCollapsingToolbarLayout)
    CollapsingToolbarLayout mCollapsingToolbarLayout;
    @Bind(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @Bind(R.id.floor_fragment)
    FrameLayout floorFragment;
    @Bind(R.id.position_fragment)
    FrameLayout positionFragment;
    @Bind(R.id.float_button)
    FloatingActionButton floatButton;
    @Bind(R.id.coordinatorLayout)
    CoordinatorLayout coordinatorLayout;
    @Bind(R.id.txt_close)
    TextView txtClose;



    private SuperviseCompanyResult.ResultEntity resultEntity;
    private CompanyBuildingVo mCompanyBuildingVo;
    /**
     * 是否是安全巡查界面过来的
     */
    private boolean isSafeInspection = false;
    private String mFloorNumber = null;
    private CompanyBuildingIndexVo mCompanyBuildingIndexVo;
    private boolean isRefresh = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void getBundleArgs() {
        if (getIntent().getExtras() != null) {
            mCompanyBuildingVo = (CompanyBuildingVo) getIntent().getSerializableExtra(BundleKey.COMPANY_BUILD_INFO);
            resultEntity = (SuperviseCompanyResult.ResultEntity) getIntent().getSerializableExtra(BundleKey.FIRE_COMPANY_BASE_INFO);
            isSafeInspection = getIntent().getBooleanExtra(BundleKey.IS_SAFE_INSPECTION, false);
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_fire_inspection_build_item;
    }

    @Override
    protected void initTitleView() {
        setBarTitle("");

    }

    @Override
    protected void initView() {



        if (null != mCompanyBuildingVo) {
            initViewValue(mCompanyBuildingVo);
            getNetData();
        }
    }

    @Override
    protected void initHttp() {

    }

    @Override
    protected void initList() {

    }

    @Override
    protected void loadList() {

    }

    @Override
    protected void refreshView() {

    }

    @Override
    protected void callFinish() {
        mActivity.finish();
    }

    @OnClick({R.id.txt_close})
    public void onButtonClick(View v) {
        switch (v.getId()) {
            case R.id.txt_close:
                LogUtils.LOGE("点击了关闭检查");
                FirefightingUtil.fireColose(mActivity);
                break;
            default:
                break;
        }
    }



    private void initViewValue(CompanyBuildingVo companyBuildingVo) {
   /*     tvEast.setText("");
        tvSouth.setText("");
        tvWest.setText("");
        tvNorth.setText("");*/
        FirefightingUtil.fireInspectAdd(this);

        tvEast.setText("东：" + StringUtils.nullValue(companyBuildingVo.getEast()));
        tvSouth.setText("南：" + StringUtils.nullValue(companyBuildingVo.getSouth()));
        tvWest.setText("西：" + StringUtils.nullValue(companyBuildingVo.getWest()));
        tvNorth.setText("北：" + StringUtils.nullValue(companyBuildingVo.getNorth()));
        if (StringUtils.nullValue(companyBuildingVo.getRemark()).length() != 0) {
            tvRemark.setText(companyBuildingVo.getRemark());
        }
        tvBuildTitle.setText(StringUtils.nullValue(companyBuildingVo.getBuildingTitle()));
        tvType.setText(StringUtils.nullValue(companyBuildingVo.getBuildType().getName()));
        String url = StringUtils.nullValue(companyBuildingVo.getImageUrl());
        if (url.length() != 0 && !HttpUtils.isIPX(url)) {
            GlideImageLoader.loadImage(this, HttpUtils.formatFilesUrl(url), iv_build, R.mipmap.img_company_build_placeholder);
        }
        mCollapsingToolbarLayout.setTitle(companyBuildingVo.getBuildingTitle());
    }

    public void getNetData() {
        //以前的请求方式
        //SafeDataServices.init().getBuildFloorList(mCompanyBuildingVo.getBuildingId(), mFloorNumber);
        httpGetBuildItem();
    }


    /**
     * 根据楼层   获取对应方位信息
     */
    public void httpGetBuildItem() {
        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("building_id", mCompanyBuildingVo.getBuildingId());
        params.put("floor_number", mFloorNumber);

        showLoading("");
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_company_building_index_info), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                dismissLoading();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {
                            mCompanyBuildingIndexVo = mGson.fromJson(mGson.toJson(baseMode.getResult()), CompanyBuildingIndexVo.class);
                            if (null != mCompanyBuildingIndexVo) {
                                setStatusLight(mCompanyBuildingIndexVo);
                                initFloorFragment(mCompanyBuildingIndexVo);
                                initPositionFragment(mCompanyBuildingIndexVo);
                            }
                        } else {
                            ToastUtil.show(baseMode.getMsg());
                        }
                    }
                }
            }
        });

    }


    /**
     * 设置标题
     *
     * @param vo
     */
    private void setStatusLight(CompanyBuildingIndexVo vo) {
        if (!isSafeInspection) return;
        tvBuildTitle.setText(StringUtils.nullValue(vo.getBuildingTitle()));
    }


    /**
     * 初始化楼层
     *
     * @param vo
     */
    private void initFloorFragment(CompanyBuildingIndexVo vo) {
        try {
            Bundle bundle = new Bundle();
            bundle.putSerializable(BundleKey.COMPANY_BUILDING_FLOOR_NUMBERS, (Serializable) vo.getFloorNumberList());
            bundle.putSerializable(BundleKey.IS_SAFE_INSPECTION, isSafeInspection);
            FireInspectionBuildingFloorFragment fragment = FireInspectionBuildingFloorFragment.newInstance();
            fragment.setArguments(bundle);
            replaceFragment(R.id.floor_fragment, fragment);

            if (mFloorNumber == null) {
                try {
                    mFloorNumber = vo.getFloorNumberList().get(0).getItemTitle();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化方位
     *
     * @param vo
     */
    private void initPositionFragment(CompanyBuildingIndexVo vo) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_ITEM_COUNT, (Serializable) vo.getItemCountlist());
        bundle.putBoolean(BundleKey.IS_SAFE_INSPECTION, isSafeInspection);
        Fragment fragment = FireInspectionBuildingPositionFragment.newInstance();
        fragment.setArguments(bundle);
        replaceFragment(R.id.position_fragment, fragment);
    }


    /**
     * http处理请求的处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {
        if (EventTag.TAG_SAFE_DATA_COLLECTION_BUILDING_INDEX_INFO.equals(event.getTag())) {//获取绑定信息
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.hidden();
                    mCompanyBuildingIndexVo = (CompanyBuildingIndexVo) event.getObj();
                    if (null != mCompanyBuildingIndexVo) {
                        setStatusLight(mCompanyBuildingIndexVo);
                        initFloorFragment(mCompanyBuildingIndexVo);
                        initPositionFragment(mCompanyBuildingIndexVo);
                    }
                } else {
                    LogUtils.LOGE(event.toString());
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        } else if (EventTag.TAG_SAFE_DATA_COLLECTION_BUILDING_POSITION_REMARK.equals(event.getTag())) {//获取绑定信息
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.hidden();
                    getNetData();
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }

    /**
     * 修改备注
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final BuildingPositionRemarkEvent event) {

        new MaterialDialog.Builder(this).title(DataInfo.getChinesePosition(event.getData().getPositionMark())).content(R.string.build_position_dialog_content).inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS).positiveText(R.string.submit_str).inputRange(2, 20).input(getString(R.string.build_position_dialog_hint), StringUtils.nullValue(event.getData().getPositionTitle()), false, new MaterialDialog.InputCallback() {
            @Override
            public void onInput(@NonNull MaterialDialog dialog, final CharSequence input) {
                if (null != input && input.toString().length() != 0) {
                    SafeDataServices.init().saveBuildingPositionRemark(input.toString(), event.getData());
                }
            }
        }).show();

    }

    /**
     * 添加检查项目
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(BuildingAddCheckItemEvent event) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(BundleKey.COMPANY_BUILD_INFO, mCompanyBuildingVo);
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_ITEM_COUNT, event.getData());
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_INDEX_VO, mCompanyBuildingIndexVo);
        UIHelper.showActivity(FireInspectionBuildItemActivity.this, bundle, FireInspectionBuildItemAddActivity.class);
    }

    /**
     * 查看已有的检查项目
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(BuildingItemCountEvent event) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(BundleKey.COMPANY_BUILD_INFO, mCompanyBuildingVo);
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_ITEM_COUNT, event.getData());
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_INDEX_VO, mCompanyBuildingIndexVo);
        UIHelper.showActivity(mActivity, bundle, FireInspectionBuildItemListActivity.class);
    }


    /**
     * 刷新界面
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(BuildingPositionRefreshEvent event) {
        if (BuildingPositionRefreshEvent.class.getName().equals(event.getTag())) {
            Log.e("test:", "刷新界面  getNetData()");
            isRefresh = true;
          /*  getNetData();
            //通知第一个页面，即建筑列表页面刷新
            AppService.getBus().post(new BuildingListFragmentRefresh());*/
        }
    }


    /**
     * 楼层事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(FloorNumItemEvent event) {
        if (FloorNumItemEvent.class.getName().equals(event.getTag())) {
            if (StringUtils.nullValue(event.getData().getItemTitle()).length() != 0) {
                mFloorNumber = StringUtils.nullValue(event.getData().getItemTitle(), "0");
                getNetData();
            }
        }
    }

    /**
     * 刷新界面  添加项目后
     *
     * @param refreshViewEntity
     */
    @Subscribe
    public void onEventMainThread(RefreshViewEntity refreshViewEntity) {
        if (FireInspectionBuildItemAddActivity.class.getName().equals(refreshViewEntity.getTAG())) {
            Log.e("test:", "刷新界面  getNetData()");
            getNetData();
        }
    }



    public void getNetData(String floorNumber) {
        mFloorNumber = floorNumber;
        getNetData();
    }





    @Override
    protected void onResume() {
        super.onResume();

        if (isRefresh) {
            isRefresh = false;
            getNetData();
            //通知第一个页面，即建筑列表页面刷新
            AppService.getBus().post(new BuildingListFragmentRefresh());
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
